<template>
  <div class="webchat_chat_info chat_info_box webchat_quick_reply_old">
    <el-tabs
            @tab-click="handleTabClick"
            class="quickreply_box">
      <!-- 自定义快捷回复 -->
      <el-tab-pane :label="$t('webchat.customize')" >
        <!-- 模糊搜索 -->
        <input-search
                class="search_box"
                :placeHolder="$t('webchat.searchQuickReply')"
                @quickSearch="quickSearch"
                :form="custSearchForm">
        </input-search>
        <!-- 自定义快捷回复列表 -->
        <el-row class="quickreply_cust_box" v-show="!custIsSearch">
          <!-- 分类列表 -->
          <div class="quickreplay_custom_con_box relative">
            <ul class="tree" v-show="customQuickReply.length">
              <li class="quickReSys quickReSysIndex" v-for="(model, index) in customQuickReply" :key="model.name + index">
                <div class="cursor_li sys_quick_li" :index="index" @click.stop="custLiActive(model, index)">
                  <span class="sys_quick_li_span">
                    <i :class="custOpenIndex.index === index && custOpenIndex.isOn ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"></i>
                  </span>
                  <div class="cata-name ellipsis sys_quick_li_title">{{model.name}}</div>
                </div>
                <ul class="quickreplay_custom_con" v-show="custOpenIndex.index === index && custOpenIndex.isOn === true">
                  <li class="quickReLi" v-for="(item, index) in currentCustomReply" :key="item.content + index">
                    <span class="quick-re-con" style="-webkit-box-orient: vertical" :title="item.content"><b v-show="item.quickContent">{{item.quickContent}}</b>{{item.content}}</span>
                    <span class="quickReBtn vertical-align">
                      <el-tooltip :content="$t('webchat.send')" placement="bottom">
                        <i class="quickRe iconfont icon-fasong1" @click.stop="quickSendMsg(item, 'cust')"></i>
                      </el-tooltip>
                      <el-tooltip :content="$t('public.paste')" placement="bottom">
                        <i class="quickRe iconfont icon-fuzhi1" @click.stop="quickCopyMsg(item, 'cust')"></i>
                      </el-tooltip>
                    </span>
                  </li>
                </ul>
              </li>
            </ul>
            <div class="quickreply_custome_btn clearfix">
              <el-button class="edit-btn" @click.stop="editCustSort" type="text" size="small">编辑自定义快捷回复</el-button>
            </div>
          </div>
        </el-row>
        <!-- 自定义快捷回复搜索结果 -->
        <el-row class="quickreply_cust_box" v-show="custIsSearch">
          <!-- 自定义快捷回复搜索结果 -->
          <div class="quickreply_custome" v-show="searchCustQuickReply.length">
            <ul class="quickreplay_custom_con tree">
              <li class="quickReSys quickReSysIndex" v-for="(model, index) in searchCustQuickReply" :key="model.name + index">
                <div class="cursor_li sys_quick_li" :index="index" @click.stop="searchLiActive(model, index, 'agent')">
                  <span class="sys_quick_li_span">
                    <i :class="custOpenIndexSearch.index === index && custOpenIndexSearch.isOn ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"></i>
                  </span>
                  <div class="cata-name ellipsis sys_quick_li_title">{{model.name}}</div>
                </div>
                <ul class="quickreplay_custom_con" v-show="custOpenIndexSearch.index === index && custOpenIndexSearch.isOn === true">
                  <li class="quickReLi" v-for="(item, index) in model.childQuickReply" :key="item.content + index">
                    <span class="quick-re-con" style="-webkit-box-orient: vertical" :title="item.content"><b v-show="item.quickContent">{{item.quickContent}}</b>{{item.content}}</span>
                    <span class="quickReBtn vertical-align">
                      <el-tooltip :content="$t('webchat.send')" placement="bottom">
                        <i class="quickRe iconfont icon-fasong1" @click.stop="quickSendMsg(item, 'cust')"></i>
                      </el-tooltip>
                      <el-tooltip :content="$t('public.paste')" placement="bottom">
                        <i class="quickRe iconfont icon-fuzhi1" @click.stop="quickCopyMsg(item, 'cust')"></i>
                      </el-tooltip>
                    </span>
                  </li>
                </ul>
              </li>
            </ul>
          </div>
          <div class="quickreply_public_none" v-show="searchCustQuickReply.length === 0">
            {{$t('webchat.noData')}}
          </div>
        </el-row>
      </el-tab-pane>
      <!-- 公共快捷回复 -->
      <el-tab-pane :label="$t('webchat.systemCommon')">
        <!-- 模糊搜索 -->
        <input-search
                class="search_box"
                :placeHolder="$t('webchat.searchQuickReply')"
                @quickSearch="quickSearch"
                :form="publicSearchForm">
        </input-search>
        <!--公共快捷回复列表-->
        <el-row class="quickreply_public" v-show="!sysIsSearch">
          <ul class="tree" v-show="sysQuickReply.length">
            <li class="quickReSys quickReSysIndex" v-for="(model, index) in sysQuickReply" :key="model.name + index">
              <div class="cursor_li sys_quick_li" @click.stop="quickSysLitoggle1(index, model)" :index="index">
                <span class="sys_quick_li_span"><i :class="publicOpen.index===index&&publicOpen.isOn ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"></i></span>
                <div class="cata-name ellipsis sys_quick_li_title">{{model.name}}</div>
              </div>
              <ul v-show="publicOpen.index === index && publicOpen.isOn === true && model.children && model.children.length" class="quick_re_sys_ul">
                <li class="quickReSys quickReLi" v-for="(item, i) in model.children" v-show="trimFun(item)" :key="item.content + i">
                  <span class="cata-name quick-re-con" style="-webkit-box-orient: vertical" :title="item.content"><b v-show="item.quickContent">{{item.quickContent}}</b>{{item.content}}</span>
                  <span class="quickReBtn vertical-align">
                    <el-tooltip :content="$t('webchat.send')" placement="bottom">
                      <i class="quickRe iconfont icon-fasong1" @click.stop="quickSendMsg(item, 'system')"></i>
                    </el-tooltip>
                    <el-tooltip :content="$t('public.paste')" placement="bottom">
                      <i class="quickRe iconfont icon-fuzhi1" @click.stop="quickCopyMsg(item, 'system')"></i>
                    </el-tooltip>
                  </span>
                </li>
              </ul>
            </li>
          </ul>
        </el-row>
        <!-- 公共快捷回复搜索结果 -->
        <el-row class="quickreply_cust_box" v-show="sysIsSearch">
          <!-- 公共快捷回复搜索结果 -->
          <div class="quickreply_public_con" v-show="searchSysQuickReply.length">
            <ul class="quick_re_sys_ul tree">
              <li class="quickReSys quickReSysIndex" v-for="(model, index) in searchSysQuickReply" :key="model.name + index">
                <div class="cursor_li sys_quick_li" @click.stop="searchLiActive(model, index, 'system')" :index="index">
                  <span class="sys_quick_li_span"><i :class="publicOpenSearch.index===index&&publicOpenSearch.isOn ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"></i></span>
                  <div class="cata-name ellipsis sys_quick_li_title">{{model.name}}</div>
                </div>
                <ul v-show="publicOpenSearch.index === index && publicOpenSearch.isOn === true && model.childQuickReply && model.childQuickReply.length" class="quick_re_sys_ul">
                  <li class="quickReSys quickReLi" v-for="(item, i) in model.childQuickReply" v-show="trimFun(item)" :key="item.content + i">
                    <span class="cata-name quick-re-con" style="-webkit-box-orient: vertical" :title="item.content"><b v-show="item.quickContent">{{item.quickContent}}</b>{{item.content}}</span>
                    <span class="quickReBtn vertical-align">
                    <el-tooltip :content="$t('webchat.send')" placement="bottom">
                      <i class="quickRe iconfont icon-fasong1" @click.stop="quickSendMsg(item, 'system')"></i>
                    </el-tooltip>
                    <el-tooltip :content="$t('public.paste')" placement="bottom">
                      <i class="quickRe iconfont icon-fuzhi1" @click.stop="quickCopyMsg(item, 'system')"></i>
                    </el-tooltip>
                  </span>
                  </li>
                </ul>
              </li>
            </ul>
          </div>
          <div class="quickreply_public_none" v-show="searchSysQuickReply.length === 0">
            {{$t('webchat.noData')}}
          </div>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script type="text/javascript">
  import inputSearch from '../../public-modules/card/search/InputSearch'
  import webchatQuickReplyEdit from './WebchatQuickReplyEdit.vue'
  import bus from '../../../store/eventBus'
  import { orderBy } from 'lodash'
  import { deepClone } from '../../../utils/m7Utils'
  // import * as types from '../../../store/modules/webchat/mutation-types.js'
  function getQuickReplyByCategory (store, data) {
    return store.dispatch('getQuickReplyByCategory', data)
  }
  export default {
    name: 'WebchatQuickReplyOld',
    data () {
      return {
        editQuickReplyId: '',   //  编辑快捷回复的id
        publicOpen: {
          index: -1,
          isOn: true
        },
        publicOpenSearch: {
          current: '',
          index: -1,
          isOn: true
        },
        custOpenIndex: {
          index: 0,
          isOn: true
        },
        custOpenIndexSearch: {
          current: '',
          index: 0,
          isOn: true
        },
        custQkReplyRandom: 0,
        editData: {
          data: []
        },
        webchatDefault: {
          remark: '',
          duration: '',
          endTime: '',
          firstReplyTime: '',
          manualTime: '',
          beginDate: '',
          username: '',
          finishReason: ''
        },
        publicSearchForm: {
          query: ''
        },
        custSearchForm: {
          query: ''
        },
        btnTitle: '',
        currentCategoryId: '',
        currentCategoryName: '',
        searchCustQuickReply: [],
        searchSysQuickReply: [],
        scopeTab: 'custom',
//        quickReplyPublic: [],
        dialogTodoType: 'list',
        dialogTitile: '',
        sysFirstClick: false, // 是否第一次加载公共快捷回复
        dialogShow: false,
        sysIsSearch: false,
        custIsSearch: false,
        changeSortFlag: false,
        sysQuickReply: [],
        customQuickReply: [],
        currentCustomReply: [],
        changeSortCategoryId: ''
      }
    },
    methods: {
      changeQuickReplySrt (data) {
        if (data.idList.length > 0) {
          let pre = this.customQuickReply.find((item) => { return item._id === data.preCategoryId })
          let next = this.customQuickReply.find((item) => { return item._id === data.nextCategoryId })
          if (pre.children && pre.children.length > 0) {
            data.idList.forEach((replyId) => {
              let preIndex = pre.children.findIndex((item) => {
                return item._id === replyId
              })
              pre.children.splice(preIndex, 1)
            })
          }
          if (next.children) {
            let categoryId = next._id === 'all' ? '' : next._id
            this.$store.dispatch('getQuickReplyByCategory', {'moduleType': 'webchat', 'categoryId': categoryId}).then((res) => {
              if (res && res.success) {
                let nextIndex = this.customQuickReply.findIndex((item) => { return item._id === data.nextCategoryId })
                next.children = deepClone(res.quickreplys)
                this.customQuickReply.splice(nextIndex, 1, next)
                let newData = this.customQuickReply.find((item) => { return item._id === (this.currentCategoryId || 'all') })
                if (newData && newData.children && newData.children.length > 0) {
                  this.currentCustomReply = newData.children
                }
                this.dialogShow = false
              }
            })
          } else {
            let newData = this.customQuickReply.find((item) => { return item._id === (this.currentCategoryId || 'all') })
            if (newData && newData.children && newData.children.length > 0) {
              this.currentCustomReply = newData.children
            }
            this.dialogShow = false
          }
        }
      },
      trimFun (data) {
        let content = deepClone(data.content)
        let conNew = content.replace(/\s/g, '')
        if (conNew) {
          return true
        } else {
          return false
        }
      },
      quickSysLitoggle1 (index, model) {
        let self = this
        if (!self.sysQuickReply[index]) {
          return
        }
        if (index === self.publicOpen.index) {
          self.publicOpen.isOn = !self.publicOpen.isOn
        } else {
          self.publicOpen.index = index
          self.publicOpen.isOn = true
        }
        if (!self.sysQuickReply[index].children) {
          let data = {
            tagParentId: model._id,
            moduleType: 'webchat'
          }
          self.$store.dispatch('newQueryQuickReply', data).then(res => {
            if (res && res.success) {
              let data = self.sysQuickReply[index]
              let resData = self.queueSort(deepClone(res.data))
              this.$set(self.sysQuickReply[index], 'children', resData)
              self.sysQuickReply.splice(index, 1, data)
            }
          })
        } else {
//          self.quickReplyPublic = self.sysQuickReply[index].children
        }
      },
      custLiActive (item, index) {
        if ((item._id === 'all' && this.currentCategoryId === '') || item._id === this.currentCategoryId) {
          this.custOpenIndex.isOn = !this.custOpenIndex.isOn
          return
        }
        if (item._id === 'all') {
          this.currentCategoryId = ''
        } else {
          this.currentCategoryId = item._id || ''
        }
        if (this.customQuickReply[index] && this.customQuickReply[index].children) {
          this.currentCustomReply = this.customQuickReply[index].children
        } else {
          this.$store.dispatch('newQueryAgentQuickReply', {'moduleType': 'webchat', 'tagParentId': this.currentCategoryId}).then((res) => {
            if (res && res.success) {
              let data = this.customQuickReply[index]
              data.children = res.data
              this.customQuickReply.splice(index, 1, data)
              this.currentCustomReply = res.data
            }
          })
        }
        this.dialogShow = false
        if (index === this.custOpenIndex.index) {
          this.custOpenIndex.isOn = !this.custOpenIndex.isOn
        } else {
          this.custOpenIndex.index = index
          this.custOpenIndex.isOn = true
        }
      },
      searchLiActive (item, index, type) {
        if (type === 'agent') {
          if (item._id === this.custOpenIndexSearch.current) {
            this.custOpenIndexSearch.isOn = !this.custOpenIndexSearch.isOn
          } else {
            this.custOpenIndexSearch.current = item._id
            this.custOpenIndexSearch.index = index
            this.custOpenIndexSearch.isOn = true
          }
        } else {
          if (item._id === this.publicOpenSearch.current) {
            this.publicOpenSearch.isOn = !this.publicOpenSearch.isOn
          } else {
            this.publicOpenSearch.current = item._id
            this.publicOpenSearch.index = index
            this.publicOpenSearch.isOn = true
          }
        }
      },
      editQuickReply (model) {
        this.currentCategoryName = model.name
        if (!model.children) {
          let categoryId = model._id === 'all' ? '' : model._id
          this.$store.dispatch('getQuickReplyByCategory', {'moduleType': 'webchat', 'categoryId': categoryId}).then((res) => {
            if (res && res.success) {
              let index = this.customQuickReply.findIndex((item) => { return model._id === item._id })
              let data = this.customQuickReply[index]
              data.children = res.quickreplys
              this.customQuickReply.splice(index, 1, data)
              this.editData = {
                data: deepClone(res.quickreplys) || []
              }
              this.custQkReplyRandom = Math.random()
              this.dialogTodoType = 'list'
              this.changeSortFlag = false
              this.changeSortCategoryId = model._id
              this.dialogTitile = '快捷语编辑'
              this.btnTitle = '增加快捷语'
              this.dialogShow = true
            }
          })
        } else {
          this.editData = {
            data: deepClone(model.children) || []
          }
          this.custQkReplyRandom = Math.random()
          this.dialogTodoType = 'list'
          this.changeSortFlag = false
          this.dialogTitile = '快捷语编辑'
          this.changeSortCategoryId = model._id
          this.btnTitle = '增加快捷语'
          this.dialogShow = true
        }
      },
//      编辑分类
      editCustSort () {
        bus.$emit('showEditCustomizeReply')
      },
      // 发送快捷回复
      quickSendMsg (data, flag) {
        if (flag === 'cust') {
          window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-发送自定义回复'])
          this.$store.dispatch('addAgentQuickReplyNum', {_id: data._id})
        }
        if (flag === 'system') {
          window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-发送公共回复'])
          this.$store.dispatch('addCommonQuickReplyNum', {_id: data._id})
        }
        let obj = {
          type: 'text',
          con: data.content
        }
        bus.$emit('quickReplyHandleSubmit', obj)
      },
      // 复制快捷回复到输入框
      quickCopyMsg (data, flag) {
        if (flag === 'cust') {
          window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-粘贴自定义回复'])
          this.$store.dispatch('addAgentQuickReplyNum', {_id: data._id})
        }
        if (flag === 'system') {
          window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-粘贴公共回复'])
          this.$store.dispatch('addCommonQuickReplyNum', {_id: data._id})
        }
        bus.$emit('quickReplyCopy', data.content)
      },
      // 搜索快捷回复
      quickSearch (data) {
        console.log(data)
        let self = this
        let dataObj = {
          type: 'agent',
          content: data,
          moduleType: 'webchat'
        }
        if (!data) {
          if (self.scopeTab === 'system') {
            self.sysIsSearch = false
            self.searchSysQuickReply = []
          } else {
            self.custIsSearch = false
            self.searchCustQuickReply = []
          }
          return
        } else {
          if (self.scopeTab === 'system') {
            dataObj.type = 'system'
          }
        }
        self.$store.dispatch('newSearchQuickReply', dataObj).then((res) => {
          if (res && res.success) {
            if (self.scopeTab === 'system') {
              self.searchSysQuickReply = res.list
              if (res.list.length) {
                self.publicOpenSearch.current = res.list[0]._id
              } else {
                self.publicOpenSearch.current = ''
              }
              self.publicOpenSearch.index = 0
              self.publicOpenSearch.isOn = true
              self.sysIsSearch = true
            } else {
              self.searchCustQuickReply = res.list
              if (res.list.length) {
                self.custOpenIndexSearch.current = res.list[0]._id
              } else {
                self.custOpenIndexSearch.current = ''
              }
              self.custOpenIndexSearch.index = 0
              self.custOpenIndexSearch.isOn = true
              self.custIsSearch = true
            }
          }
        })
      },
      handleTabClick (tab) {
        if (tab.index === '1') {
          this.scopeTab = 'system'
          if (!this.sysFirstClick) {
            this.sysFirstClick = true
            this.quickSysLitoggle1(0, this.sysQuickReply[0])
          }
        } else {
          this.scopeTab = 'custom'
        }
      },
      handleClose () {
        this.dialogShow = false
      },
      queueSort (data) {
        data = orderBy(data, [(o) => {
          let aa = o['sort'] || -1
          return aa
        }, (o) => {
          let aa = o['updatedTime'] || 0
          return aa
        }], ['asc', 'desc'])
        return data
      },
      refreshAgentReply () {
        let self = this
        self.$store.dispatch('newQueryAgentQuickReplyTag', {'moduleType': 'webchat'}).then(res => {
          if (res && res.success) {
            let resData = deepClone(res.data)
            self.customQuickReply = self.queueSort(resData)
            let currentIndex = 0
            if (!self.currentCategoryId) {
              self.currentCategoryId = self.customQuickReply[currentIndex]._id
            } else {
              self.customQuickReply.forEach((item, index) => {
                if (item._id === self.currentCategoryId) {
                  currentIndex = index
                }
              })
            }
            self.$store.dispatch('newQueryAgentQuickReply', {'moduleType': 'webchat', 'tagParentId': self.currentCategoryId}).then((res) => {
              if (res && res.success) {
                let resData = deepClone(res.data)
                self.currentCustomReply = self.queueSort(resData)
                let data = self.customQuickReply[currentIndex]
                if (!self.currentCategoryId) {
                  data = self.customQuickReply[currentIndex]
                  data.children = deepClone(res.data)
                }
                self.customQuickReply.splice(currentIndex, 1, data)
              }
            })
          }
        })
      }
    },
    computed: {
      tabType () {
        let arr = this.$route.path.split('/')
        return arr[3]
      },
      sessionId () {
        let arr = this.$route.path.split('/')
        return arr[4]
      },
      webchatData () {
        //  会话的详细信息
        if (this.tabType === 'webchat_todo' && this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId]) {
          return this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId]
        } else if (this.tabType === 'webchat_all' && this.$store.state.webchat.current.webchat_all.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_all.currentSession)
        } else if (this.tabType === 'webchat_robot' && this.$store.state.webchat.current.webchat_robot.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_robot.currentSession)
        } else if (this.tabType === 'webchat_queue' && this.$store.state.webchat.current.webchat_queue.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_queue.currentSession)
        } else {
          return {}
        }
      }
    },
    components: {
      webchatQuickReplyEdit,
      inputSearch
    },
    mounted () {
      bus.$on('changeQuickReplySrt', () => {
        getQuickReplyByCategory(this.$store, {'moduleType': 'webchat', 'categoryId': this.currentCategoryId}).then(() => {
          this.dialogShow = false
        })
      })
      bus.$on('refreshAgentReply', () => {
        this.refreshAgentReply()
        let data1 = {
          'moduleType': 'webchat'
        }
        this.$store.dispatch('getAllQuickReplyListNew', data1)
      })
    },
    beforeDestroy () {
      bus.$off('changeQuickReplySrt')
      bus.$off('refreshAgentReply')
    },
    beforeMount () {
      let self = this
      self.$store.dispatch('newQueryQuickReplyTag', {'moduleType': 'webchat'}).then((res) => {
        if (res && res.success) {
          let resData = deepClone(res.data)
          self.sysQuickReply = self.queueSort(resData)
        }
      })
      self.refreshAgentReply()
    }
  }
</script>
<style lang="stylus">
  @import "../../../assets/common.styl"
  .webchat_todo_conbox
    .basic_info
      .el-form
        padding 0
        margin-bottom 45px
      .el-col.el-col-24.full-add ,.el-col.el-col-24.full-del
        position absolute
        top -2px
        margin-left -6px
  .quickreplay_li
    .edit_del
      position absolute
      right 4px
      top 0
      padding 2px 0
  .vertical-align:after
    display inline-block
    width 0
    height 100%
    content "center"
    vertical-align middle
    overflow hidden
  .relative
    position relative
    .quickreply_custome_btn
      position absolute
      bottom 0
      left 0
      width 100%
      -webkit-box-sizing border-box
      box-sizing border-box
      background #fafafa
      -webkit-box-shadow 0px 0px 8px rgba(0,0,0,0.15)
      box-shadow 0px 0px 8px rgba(0,0,0,0.15)
      text-align center
      padding 10px 0
  .quickreplay_custom_con_box
    height calc(100vh - 174px)
    .tree
      height calc(100vh - 228px)
      overflow-y auto
  .quickReSysIndex
    position relative
  .webchat_reply_tooltip
    word-break break-all
  .quick-re-con
    b
      font-weight normal
      padding-right 10px
      color #000
  .quickreply_public_none
    padding 0 10px
</style>
<style lang="stylus" scoped>
  @import "./style/webchatCon.styl"
</style>